import store from "@/store";
import { ThemeModel, setTheme } from "@/store/modules/appSlice";
import { localStorage } from "@/utils/storage";

/** app主题类 */
export class UseTheme {
  rootElement: HTMLElement | null = null;
  constructor() {
    this.rootElement = document.body;
  }
  /**
   * 设置主题的css变量
   * @param themeName 主题名称
   * @param colorList 颜色列表：rgb格式
   */
  setThemeVars(themeName: string, colorList?: string[]) {
    this.rootElement!.className = themeName;
    if (colorList?.length) {
      colorList.forEach((el: string, index: number) => {
        this.rootElement!.style.setProperty(
          `--primary-${index + 1}`,
          this.getColor(el)
        );
      });
    }
  }
  setVar(varName: string, value: string) {
    this.rootElement!.style.setProperty(varName, value);
  }
  /**
   * 设置保存的主题色
   */
  setLocalTheme() {
    const theme = localStorage.get("theme") as ThemeModel;
    if (theme) {
      this.setThemeVars(theme.key, theme.colorList);
      store.dispatch(setTheme(theme));
    }
  }

  getLocalTheme() {
    const theme = localStorage.get("theme") as ThemeModel;
    return theme;
  }
  /**
   *
   * @param theme 保存主题到本地
   */
  saveLocalTheme(theme: ThemeModel) {
    localStorage.set("theme", theme);
  }

  /**
   * 主题设为默认
   */
  resetTheme() {
    this.rootElement!.className = "";
  }
  /**
   * 获取rgb颜色的数值
   * @param rgb rgb格式的颜色
   * @returns
   */
  getColor(rgb: string) {
    const regex = /rgb\(([^)]+)\)/;
    return rgb.match(regex)?.[1] || "";
  }

  /** 获取当前主题名称 */
  getCurrentTheme() {
    return this.rootElement?.className || "";
  }

  /** 获取设置的css变量 */
  getVar(name: string) {
    const computedStyle = window.getComputedStyle(this.rootElement!);
    return `rgb(${computedStyle.getPropertyValue(name)})`;
  }
}

export default new UseTheme();
